﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using IWMAG.Scripting.AST.ObjectModel;
using IWMAG.Scripting.AST.Declarations;
using IWMAG.Scripting.Interpreter;
using IWMAG.Scripting.Types;

namespace IWMAG.Scripting.AST.Statements {
    internal class VariableDeclarationStatement : CodeStatement {
        public VariableDeclaration Declaration;

        public VariableDeclarationStatement(Compiler.Lexeme l, VariableDeclaration decl) : base(l) {
            Declaration = decl;
        }

        public override void Verify(Helpers.CompileTable sym, List<Compiler.IUserInfo> error) {
            Declaration.Verify(sym, error);

            sym.Variables[Declaration.Name] = sym.Dealias(Declaration.Type);
        }

        public override IEnumerable<Continuation> Execute(Interpreter.ScriptEngine engine, Helpers.RuntimeTable sym) {
            if (Declaration.InitialValue != null) {
                Reference<RunValue> val = RunValue.NoValue;
                foreach (Continuation wait in Declaration.InitialValue.ValueOf(engine, sym, val)) yield return wait;
                sym.Variables[Declaration.Name] = val;
            } else if (Declaration.Type is ArrayType) {
                sym.Variables[Declaration.Name] = new RunValue(new ArrayRunValue());
            } else {
                sym.Variables[Declaration.Name] = RunValue.NoValue;
            }
        }
    }
}
